const { categoryError, checkIdExist, checkIdError, checkCategoryExist, checkIdfatherExist, searchcategory_nameError } = require('../constant/err.type.js')
const { getCategoryChildById, getCategoryById, getCategoryfatherById, checkCategoryBycategory_name } = require('../service/category.service.js')
// 格式校验
const validator = (rules) => {
    return async (ctx, next) => {
        try {
            // 校验格式
            ctx.verifyParams(rules)
        } catch (err) {
            // 返回错误信息
            console.error(err);
            categoryError.result = err
            return ctx.app.emit('error', categoryError, ctx)
        }
        await next()
    }

}
async function checkDuplicateCategory(ctx, next) {
    const { category_name } = ctx.request.body;
    try {
        const res = await checkCategoryBycategory_name(category_name);
        if (res) {
            console.error("分类名已经存在", { category_name });
            ctx.app.emit('error', searchcategory_nameError, ctx);
            return
        }
    } catch (err) {
        console.error("分类名已经存在", err);
        ctx.app.emit('error', checkIdError, ctx);
        return
    }
    await next();
}

// 检查是否有子类别
const checkIdChild = async (ctx, next) => {
    const id = ctx.params.id
    // 合理性
    try {
        const res = await getCategoryChildById(id);
        if (res) {
            console.error("有子类别，不能删除", "错误信息:", { id });
            ctx.app.emit('error', checkIdExist, ctx);
            return
        }
    } catch (err) {
        console.error("获取商品分类id失败", err);
        ctx.app.emit('error', checkIdError, ctx);
        return
    }
    await next();
}

// 查询商品类别是否存在
const checkId = async (ctx, next) => {
    const { id } = ctx.request.body;
    // 合理性
    try {
        const res = await getCategoryById(id);
        if (!res) {
            console.error("没有该商品类别", { id });
            ctx.app.emit('error', checkCategoryExist, ctx);
            return
        }
    } catch (err) {
        console.error("获取商品分类id失败", err);
        ctx.app.emit('error', checkIdError, ctx);
        return
    }
    await next();
}
const checkIdfather = async (ctx, next) => {
    const { parent_category_id } = ctx.request.body;
    if (parent_category_id === 0 || parent_category_id === null || parent_category_id === undefined) {
        return await next();
    }
    // 合理性
    try {
        const res = await getCategoryfatherById(parent_category_id);
        if (!res) {
            console.error("没有该父类商品类别", { parent_category_id });
            ctx.app.emit('error', checkIdfatherExist, ctx);
            return
        }
    } catch (err) {
        console.error("获取商品分类id失败", err);
        ctx.app.emit('error', checkIdError, ctx);
        return
    }
    await next();
}




module.exports = {
    validator,
    checkIdChild,
    checkId,
    checkIdfather,
    checkDuplicateCategory
}